package com.xiguanlezz.cn.scanner;

import com.xiguanlezz.cn.annotation.RpcReference;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/3 14:00
 * @Description：服务消费者注解扫描器（扫描成员变量上是否有@RpcReference注解）
 */
@Slf4j
public class RpcReferenceScanner extends ClassScanner {

    public static Map<String, Object> doScanAndCreateProxyObj(String packageName) {
        Map<String, Object> handlerMap = new HashMap<>();

        try {
            List<String> classNameList = getClassNameList(packageName);
            for (String className : classNameList) {
                Class<?> clazz = Class.forName(className);
                Field[] fields = clazz.getDeclaredFields();
                if (isEmpty(fields)) {
                    continue;
                }

                for (Field field : fields) {
                    RpcReference rpcReferenceAnno = field.getAnnotation(RpcReference.class);
                    if (Objects.nonNull(rpcReferenceAnno)) {
                        log.info("@RpcReference field：============> {}", field.getName());
                        log.info("@RpcReference version：============> {}", rpcReferenceAnno.version());
                        log.info("@RpcReference group：============> {}", rpcReferenceAnno.group());
                        log.info("@RpcReference registryType：============> {}", rpcReferenceAnno.registryType());
                        log.info("@RpcReference registryAddress：============> {}", rpcReferenceAnno.registryAddress());
                        log.info("@RpcReference dynamicProxyType：============> {}", rpcReferenceAnno.dynamicProxyType());
                        log.info("@RpcReference serializableType：============> {}", rpcReferenceAnno.serializableType());
                        log.info("@RpcReference invokeMethodType：============> {}", rpcReferenceAnno.invokeMethodType());
                        log.info("@RpcReference invokeTimeout：============> {}", rpcReferenceAnno.invokeTimeout());
                        log.info("@RpcReference loadBalanceType：============> {}\n", rpcReferenceAnno.loadBalanceType());
                    }
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        return handlerMap;
    }

    private static boolean isEmpty(Field[] fields) {
        return Objects.isNull(fields) || fields.length == 0;
    }
}
